//
//  SWBasketEventPageViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/11.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWBasketEventPageViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,TableViewCellDelegate
{
    private var _books:[SWBook] = []
    private var _pages:[SWPageProduct] = []
    //当前选中的书
    private var _bookID:String = ""
    
    private var _nameLabel:UILabel = UILabel()
    private var _countLabel:UILabel = UILabel()
    lazy private var _tableView:UITableView = UITableView()
    
    deinit
    {
        SWNotificationCenter.removeObserver(self)
        trace("DEINIT SWBasketEventPageViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillLayoutFirstTime() {
        setup()
    }
    
    private func setup()
    {
        let lastY = createTopBar()
        
        _tableView.frame = CGRectMake(0, lastY, view.width, view.height - lastY)
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = 120
        _tableView.separatorInset = UIEdgeInsets.zero
        view.addSubview(_tableView)
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = UIEdgeInsets.zero
        }
        
        
        _books = SWBookManager.sharedManager().books.filter({$0.category == .event})
        
        if let book = _books.valueAt(0)
        {
            selectBook(book)
        }
        
        SWNotificationCenter.addObserver(self, selector: #selector(pageCompletedManualNotification(_:)), name: NotificationName.PageCompletedManual, object: nil)
        
        SWNotificationCenter.addObserver(self, selector: #selector(pageProductCountChangedNotification), name: NotificationName.PageProductCountChanged, object: nil)
    }
    
    private func createTopBar() -> CGFloat
    {
        let statusView:UIView = UIView()
        statusView.frame = CGRectMake(0, 0, view.width, 30)
        statusView.backgroundColor = UIColor(white: 0.94, alpha: 1)
        view.addSubview(statusView)
        
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(statusViewTapped))
        statusView.addGestureRecognizer(tapGesture)
        
        _nameLabel.font = UIFont.systemFont(ofSize: 14)
        _nameLabel.textColor = UIColor.darkGray
        _nameLabel.frame = CGRectMake(0, 0, 100, statusView.height)
        statusView.addSubview(_nameLabel)
        
        _countLabel.font = UIFont.systemFont(ofSize: 14)
        _countLabel.textColor = UIColor.darkGray
        _countLabel.frame = CGRectMake(_nameLabel.right, 0, 100, statusView.height)
        statusView.addSubview(_countLabel)
        
        return statusView.bottom
    }
    
    private func selectBook(_ book:SWBook)
    {
        _pages.removeAll()
        _bookID = book.bookID ?? ""
        if let pages = book.pages?.flatMap({$0 as? SWPage}),pages.count > 0
        {
            _pages = pages.map({SWPageProduct(page:$0)})
            for page in _pages
            {
                page.selected = SWTransactionManager.sharedManager().basketContains(page:page)
            }
        }
        _tableView.reloadData()
        _nameLabel.text = book.title
        pageProductCountChanged()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWBasketEventPageCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: Identifier) as? SWBasketEventPageCell
        if cell == nil
        {
            cell = SWBasketEventPageCell(style: .default, reuseIdentifier: Identifier, cellWidth: view.width)
            (cell as? SWBasketEventPageCell)?.delegate = self
        }
        (cell as? SWBasketEventPageCell)?.product = _pages.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _pages.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        if let page = _pages.valueAt(indexPath.row)
        {
            
        }
    }
    
    func tableViewCell(_ cell:UITableViewCell, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Select
        {
            if let product = (cell as? SWBasketEventPageCell)?.product
            {
                product.selected = true
                SWTransactionManager.sharedManager().addToBasket(page: product)
            }
        }
        else if action == CallbackAction.Deselect
        {
            if let product = (cell as? SWBasketEventPageCell)?.product
            {
                product.selected = false
                SWTransactionManager.sharedManager().removeFromBasket(page: product)
            }
        }
    }
    
    @objc private func statusViewTapped()
    {
        if _books.count == 0{
            return
        }
        
        let chooseViewController = SWBookChooseViewController(books:_books)
        chooseViewController.chooseCallback = {[weak self] index in
            if let book = self?._books.valueAt(index)
            {
                self?.selectBook(book)
            }
        }
        navigationController?.pushViewController(chooseViewController, animated: true)
    }
    
    @objc private func pageCompletedManualNotification(_ notification:Notification)
    {
        if let pageID = notification.userInfo?[SWKey.pageID] as? String,pageID != "",
            let index = _pages.index(where: {($0.page.pageID ?? "") == pageID})
        {
            _tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
        }
    }
    
    private func pageProductCountChanged()
    {
        let count:Int = SWTransactionManager.sharedManager().pages.filter({($0.page.bookID ?? "") == _bookID}).count
        _countLabel.text = "已选\(count)个"
    }
    
    @objc private func pageProductCountChangedNotification()
    {
        pageProductCountChanged()
    }
    
    
}
